<template>
  <div
    class="drag-wrapper"
    @mousedown="handleDown"
    :style="{ top: positionY + 'px', right: positionX + 'px' }"
    ref="dragWrapper"
    :class="[wrapClass]"
  >
    <slot></slot>
  </div>
</template>
<script>
export default {
  name: "VDrag",
  props: {
    wrapClass: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      isDown: false,
      positionX: 0,
      positionY: 0,
      current: {
        x: 0,
        y: 0,
      },
      dis: {
        // 点击点与元素的两个方向上的距离
        x: 0,
        y: 0,
      },
      $dragEl: null, // 拖拽的元素
    }
  },
  mounted() {
    document.addEventListener("mouseup", (ev) => {
      this.isDown = false
      document.removeEventListener("mousemove", this.handleMove.bind(this))
      const absX = Math.abs(this.current.x - ev.clientX)
      const absY = Math.abs(this.current.y - ev.clientY)
      const clkDis = 3
      // 如果横竖两个方向的位移都小于3，则认为是点击事件
      if (absX < clkDis && absY < clkDis) {
        this.$emit("onclk")
      }
    })
    document.addEventListener("mousemove", this.handleMove.bind(this))
    this.$dragEl = this.$refs.dragWrapper
  },
  computed: {
    maxRight() {
      if (this.$dragEl) {
        return document.documentElement.clientWidth - this.$dragEl.offsetWidth
      }
      return 9999
    },
    maxTop() {
      if (this.$dragEl) {
        return document.documentElement.clientHeight - this.$dragEl.offsetHeight
      }
      return 9999
    },
  },
  methods: {
    handleDown(ev) {
      this.isDown = true
      this.current.x = ev.clientX
      this.current.y = ev.clientY
      this.dis.x =
        this.$refs.dragWrapper.offsetWidth -
        (ev.clientX - this.$refs.dragWrapper.offsetLeft)
      this.dis.y = ev.clientY - this.$refs.dragWrapper.offsetTop
    },
    handleMove(ev) {
      if (this.isDown === true) {
        const R = this.limitVal(
          document.documentElement.clientWidth - ev.clientX - this.dis.x,
          "maxRight"
        )
        const T = this.limitVal(ev.clientY - this.dis.y, "maxTop")
        this.positionX = R
        this.positionY = T
      }
    },
    // 限制住在可是范围内拖拽
    limitVal(currentVal, key) {
      if (currentVal > this[key]) {
        return this[key]
      } else {
        if (currentVal < 0) {
          return 0
        } else {
          return currentVal
        }
      }
    },
  },
}
</script>
<style scoped lang="less">
.drag-wrapper {
  background-color: rgba(0, 0, 0, 0.2);
  position: fixed;
  z-index: 99999;
  cursor: move;
  user-select: none;
}
</style>
